/*
 * Copyright (c) Ulrich Hilger, http://dev.uhilger.de, all rights reserved.
 *
 * Published under the terms and conditions of the Apache License 2.0,
 * see http://www.apache.org/licenses/LICENSE-2.0
 */

package de.uhilger.servicehub;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

/**
 * Class HttpRequest provides static methods to send requests via HTTP
 * 
 * @author Ulrich Hilger, <a href="http://dev.uhilger.de" target="_blank">http://dev.uhilger.de</a>
 * @author Published under the terms and conditions of
 * the <a href="http://www.apache.org/licenses/LICENSE-2.0" target="_blank">Apache License 2.0</a>
 */
public class HttpRequest {

  /**
   * Create a new object of class HttpRequest
   */
  public HttpRequest() {
    super();
  }

  /**
   * Send an HTTP GET request
   *
   * @param urlStr  the URL to send the request to
   * @return  the input stream to read the HTTP response from
   * @throws Exception
   */
  public static InputStream get(String urlStr) throws Exception {
    return readFrom(urlStr, null);
  }

  /**
   * Send an HTTP POST request
   *
   * @param urlStr  the URL to send the request to
   * @param post  the data to send with this HTTP POST request
   * @return  the input stream to read the HTTP response from
   * @throws Exception
   */
  public static InputStream post(String urlStr, String post)
          throws Exception {
    return readFrom(urlStr, post);
  }

  /**
   * Send a HTTP GET or POST request
   *
   * @param urlStr  the URL to send the request to
   * @param postStr  the data to send with this HTTP POST request or null for HTTP GET
   * @return    the input stream to read the HTTP response from
   * @throws MalformedURLException
   * @throws IOException
   */
  private static InputStream readFrom(String urlStr, String postStr)
          throws MalformedURLException, IOException {
    URLConnection conn = new URL(urlStr).openConnection();
    conn.setDoInput(true);
    if (postStr != null && postStr.length() > 0) {
      conn.setDoOutput(true);
      DataOutputStream output =
              new DataOutputStream(conn.getOutputStream());
      output.writeBytes(postStr);
      output.flush();
      output.close();
    }
    return conn.getInputStream();
  }
}
